<template>
  <el-dialog :visible.sync="visible" title="选择配送范围" width="800px" append-to-body @close="closeDialog">
    <div style="margin-bottom: 8px; display: flex; align-items: center">
      <el-select
        v-model="selectedPoiIndex"
        filterable
        remote
        :remote-method="handleSearch"
        placeholder="请输入位置关键词"
        size="small"
        style="width: 300px"
        @change="handlePoiSelect"
        :loading="searchLoading"
        :clearable="true"
        :popper-append-to-body="false"
      >
        <el-option
          v-for="(item, idx) in searchResults"
          :key="idx"
          :label="item.name + (item.address ? '（' + item.address + '）' : '')"
          :value="idx"
        />
      </el-select>
      <el-button size="small" type="primary" icon="el-icon-search" style="margin-left: 8px" @click="triggerSearch"
        >搜索</el-button
      >
    </div>
    <div id="deliveryMap" style="height: 400px"></div>
    <div style="margin-top: 10px">
      <el-button size="mini" @click="clearPolygon">清空围栏</el-button>
      <span>
        当前围栏点数：{{ polygonPath.length }}
      </span>
    </div>
    <span slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary"  @click="confirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'DeliveryMapDialog',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    center: {
      type: String,
      default: '', // "lng,lat"
    },
    radius: {
      type: Number,
      default: 1000, // 兼容旧用法
    },
    polygons: {
      type: Array,
      default: () => [],
    },
    roomPosition: {
      type: String,
      default: '[114.305393, 30.593099]',
    },
    rangeList:{
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      map: null,
      polygon: null,
      polygonPath: [],
      localCenter: this.center ? this.center.split(',').map(Number) : [114.305393, 30.593099],
      mapLoaded: false,
      searchKeyword: '',
      searchMarker: null,
      searchResults: [],
      selectedPoiIndex: null,
      searchLoading: false,
      pointMarkers: [],
      circleMarker: null, // 中心点marker
      referenceCircle: null, // 虚线圆
      rangePolygons: [],
    };
  },
  computed: {
    polygonArea() {
      if (this.polygonPath.length < 3 || !window.AMap || !window.AMap.GeometryUtil) return 0;
      // GeometryUtil.ringArea expects array of [lng, lat]
      return window.AMap.GeometryUtil.ringArea(this.polygonPath);
    },
    formattedArea() {
      if (this.polygonArea >= 1000000) {
        return (this.polygonArea / 1000000).toFixed(3) + ' km²';
      } else {
        return Math.round(this.polygonArea) + ' m²';
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        // console.log(val, 108);
         if (val) {
        // 回显多边形
        if (this.polygons && this.polygons.length) {
          this.polygonPath = JSON.parse(JSON.stringify(this.polygons));
        } else {
          this.polygonPath = [];
        }
        this.$nextTick(this.initMap);
      } else {
        this.polygonPath = [];
      }
      },
      deep: true,
      immediate: true,
    },
    rangeList: {
      handler() {
        if (this.map) this.renderRangeListPolygons();
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    closeDialog() {
      this.$emit('update:visible', false);
    },
    initMap() {
      console.log('initMap called, mapLoaded:', this.mapLoaded, 107);
      // if (this.mapLoaded) return;
      if (!window.AMap) {
        this.$message.error('高德地图API未加载');
        return;
      }
      let [lng, lat] = this.roomPosition ? this.roomPosition.split(',').map(Number) : [114.305393, 30.593099];
      console.log('initMap lng, lat:', lng, lat, 109);
      this._initMapWithCenter([lng, lat]);
    },
    _initMapWithCenter(center) {
      console.log('_initMapWithCenter called, center:', center);
      if (!document.getElementById('deliveryMap')) {
        console.log('deliveryMap dom not found');
        return; // 容器不存在不初始化
      }
      this.map = new window.AMap.Map('deliveryMap', {
        center: center,
        zoom: 12,
      });
      console.log('AMap.Map created');
      // 以中心点为圆心，radius（单位公里）为半径画虚线"圆"
      const pureCenter = [Number(center[0]), Number(center[1])];
      const radiusInMeters = Number(this.radius || 1) * 1000;
      console.log('this.radius:', this.radius, 'radiusInMeters:', radiusInMeters);
      // 中心点 marker
      if (this.circleMarker) {
        this.circleMarker.setMap(null);
      }
      this.circleMarker = new window.AMap.Marker({
        position: pureCenter,
        map: this.map,
        zIndex: 101,
        // content 可自定义
      });
      console.log('center marker created at:', pureCenter);
      // 用多边形模拟虚线圆
      function getCirclePoints(center, radius, numPoints = 60) {
        const [lng, lat] = center;
        const points = [];
        for (let i = 0; i < numPoints; i++) {
          const angle = (2 * Math.PI * i) / numPoints;
          // 地球半径约6378137米
          const dx = radius * Math.cos(angle);
          const dy = radius * Math.sin(angle);
          // 经纬度换算
          const dlng = (dx / (6378137 * Math.cos((lat * Math.PI) / 180))) * (180 / Math.PI);
          const dlat = (dy / 6378137) * (180 / Math.PI);
          points.push([lng + dlng, lat + dlat]);
        }
        return points;
      }
      const circlePath = getCirclePoints(pureCenter, radiusInMeters);
      if (this.referenceCircle) {
        this.referenceCircle.setMap(null);
      }
      this.referenceCircle = new window.AMap.Polygon({
        path: circlePath,
        strokeColor: "#1890ff",
        strokeOpacity: 1,
        strokeWeight: 2,
        fillOpacity: 0,
        strokeStyle: "dashed",
        strokeDasharray: [10, 10],
        map: this.map,
      });
      console.log('reference polygon circle created, center:', pureCenter, 'radius(m):', radiusInMeters);
      // 自动适应圆视野
      this.map.setFitView([this.referenceCircle]);
      // 鼠标点击添加多边形点
      this.map.on('click', this.addPolygonPoint);
      this.mapLoaded = true;
      // 回显多边形
      if (this.polygonPath && this.polygonPath.length) {
        this.drawPolygon();
      }
      // 渲染 rangeList 多边形电子围栏
      this.renderRangeListPolygons();
    },
    triggerSearch() {
      this.handleSearch(this.searchKeyword);
    },
    handleSearch(query) {
      this.searchKeyword = typeof query === 'string' ? query : this.searchKeyword;
      if (!this.searchKeyword) {
        this.searchResults = [];
        this.selectedPoiIndex = null;
        return;
      }
      if (!window.AMap) return;
      this.searchLoading = true;
      window.AMap.plugin('AMap.PlaceSearch', () => {
        const placeSearch = new window.AMap.PlaceSearch({
          pageSize: 10,
        });
        placeSearch.search(this.searchKeyword, (status, result) => {
          this.searchLoading = false;
          if (status === 'complete' && result.poiList.pois.length) {
            this.searchResults = result.poiList.pois;
          } else {
            this.searchResults = [];
            this.$message.warning('未找到相关位置');
          }
        });
      });
    },
    handlePoiSelect(idx) {
      const poi = this.searchResults[idx];
      if (!poi) return;
      const lnglat = [poi.location.lng, poi.location.lat];
      this.map.setCenter(lnglat);
      this.map.setZoom(16);
      // 标记搜索点
      if (this.searchMarker) {
        this.searchMarker.setMap(null);
      }
      this.searchMarker = new window.AMap.Marker({
        position: lnglat,
        map: this.map,
      });
    },
    addPolygonPoint(e) {
      this.polygonPath.push([e.lnglat.lng, e.lnglat.lat]);
      this.addPointMarker([e.lnglat.lng, e.lnglat.lat]);
      this.drawPolygon();
    },
    addPointMarker(lnglat) {
      if (!this.map) return;
      const marker = new window.AMap.Marker({
        position: lnglat,
        map: this.map,
        offset: new window.AMap.Pixel(-6, -6),
        content:
          '<div style="width:12px;height:12px;background:#f5222d;border-radius:50%;border:2px solid #fff;box-shadow:0 0 4px #f5222d;"></div>',
        zIndex: 100,
      });
      this.pointMarkers.push(marker);
    },
    clearPointMarkers() {
      this.pointMarkers.forEach((m) => {
        if (m && typeof m.setMap === 'function') {
          m.setMap(null);
        }
      });
      this.pointMarkers = [];
    },
    updatePointMarkers() {
      this.clearPointMarkers();
      this.polygonPath.forEach((lnglat) => this.addPointMarker(lnglat));
    },
    drawPolygon() {
      if (this.polygon) {
        this.polygon.setMap(null);
        this.polygon = null;
      }
      this.clearPointMarkers();
      if (this.polygonPath.length) {
        this.polygon = new window.AMap.Polygon({
          path: this.polygonPath,
          strokeColor: '#F33',
          strokeWeight: 3,
          fillColor: '#ee2200',
          fillOpacity: 0.2,
          editable: true,
        });
        this.polygon.setMap(this.map);
        this.polygonPath.forEach((lnglat) => this.addPointMarker(lnglat));
        // 启用编辑
        if (!this.editor) {
          window.AMap.plugin('AMap.PolygonEditor', () => {
            this.editor = new window.AMap.PolygonEditor(this.map, this.polygon);
            this.editor.open();
            this.editor.on('adjust', () => {
              this.polygonPath = this.polygon.getPath().map((p) => [p.lng, p.lat]);
              this.updatePointMarkers();
            });
            this.editor.on('end', () => {
              this.polygonPath = this.polygon.getPath().map((p) => [p.lng, p.lat]);
              this.updatePointMarkers();
            });
          });
        } else {
          this.editor.setTarget(this.polygon);
          this.editor.open();
        }
        // 保证每次都激活编辑器
        if (this.editor) {
          this.editor.setTarget(this.polygon);
          this.editor.open();
        }
      }
    },
    clearPolygon() {
      this.polygonPath.splice(0, this.polygonPath.length);
      if (this.editor) {
        this.editor.close();
        this.editor = null;
      }
      if (this.polygon) {
        this.polygon.setMap(null);
        this.polygon = null;
      }
      // if (this.circleMarker) {
      //   this.circleMarker.setMap(null);
      //   this.circleMarker = null;
      // }
      // if (this.referenceCircle) {
      //   this.referenceCircle.setMap(null);
      //   this.referenceCircle = null;
      // }
      this.clearPointMarkers();
      // 清除所有与围栏相关的缓存
      this.selectedPoiIndex = null;
      this.searchKeyword = '';
      this.searchResults = [];
      this.searchLoading = false;
      this.pointMarkers = [];

      // 通知父组件清空
      this.$emit('clearPolygons');
    },
    confirm() {
      this.$emit('select', {
        polygon: this.polygonPath,
      });
      this.close();
    },
    close() {
      this.$emit('update:visible', false);
      if (this.map) {
        try{
        this.map.off('click', this.addPolygonPoint);
        this.map.destroy();
        this.map = null;
        this.polygon = null;
        this.polygonPath = [];
        this.mapLoaded = false;
        if (this.editor) {
          this.editor.close();
          this.editor = null;
        }
        if (this.searchMarker) {
          this.searchMarker.setMap(null);
          this.searchMarker = null;
        }
        if (this.circleMarker) {
          this.circleMarker.setMap(null);
          this.circleMarker = null;
        }
        if (this.referenceCircle) {
          this.referenceCircle.setMap(null);
          this.referenceCircle = null;
        }
        this.clearPointMarkers();
        }catch(e){
          console.error('close error:', e);
          this.$emit('update:visible', false);
        }
      }
      this.searchResults = [];
      this.selectedPoiIndex = null;
      this.searchKeyword = '';
      this.searchLoading = false;
    },
    renderRangeListPolygons() {
      console.log(396);
      // 清除旧的
      if (this.rangePolygons && this.rangePolygons.length) {
        this.rangePolygons.forEach(p => p.setMap(null));
      }
      this.rangePolygons = [];
      if (!Array.isArray(this.rangeList)) return;
      const colors = ['#1890ff', '#f5222d', '#faad14', '#52c41a', '#13c2c2', '#722ed1'];
      this.rangeList.forEach((polygonPoints, idx) => {
        if (!Array.isArray(polygonPoints) || polygonPoints.length < 3) return;
        const polygon = new window.AMap.Polygon({
          path: polygonPoints,
          strokeColor: colors[idx % colors.length],
          strokeWeight: 3,
          fillColor: colors[idx % colors.length],
          fillOpacity: 0.15,
          map: this.map,
        });
        this.rangePolygons.push(polygon);
      });
    },
  },
  mounted() {
    // 只加载高德面积计算工具
    if (window.AMap && !window.AMap.GeometryUtil) {
      window.AMap.plugin('AMap.GeometryUtil');
    }
  },
};
</script>

<style scoped>
#deliveryMap {
  width: 100%;
  height: 600px;
}
</style>
